package service;

import common.Pagination;
import dao.CroMyqponDao;
import entity.CroMyqpon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/7 0007.
 */
@Service
public class CroMyqponService {

    @Autowired
    private CroMyqponDao croMyqponDao;
    @Autowired
    private CroCouponsService croCouponsService;

    /*
    * 根据id查找所有优惠券
    * */
    @Transactional(readOnly = true)
    public List<CroMyqpon> FindMyqpon(String id){
        String hql="from CroMyqpon where id=?";
        List<CroMyqpon> showMyqpon = croMyqponDao.findList(hql,id);
        return showMyqpon;
    }

    /*根据id查找一张优惠券*/
    @Transactional(readOnly = true)
    public CroMyqpon FindMyqponbyid(String id){
        CroMyqpon showMyqpon = croMyqponDao.getById(id);
        return showMyqpon;
    }
    /*
    * 根据顾客id查找当前可用的优惠券
    * */
    @Transactional(readOnly = true)
    public List<CroMyqpon> FindUseMyqponByCusId(String cusid){
        Map<String,Object> map=new HashMap<>();
        map.put("costomid",cusid);
        map.put("del_flag","0");
        map.put("status","0");
        List<CroMyqpon> croMyqpons=croMyqponDao.findByProperty(map);
        return croMyqpons;
    }

    /*
    * 更新个人使用的优惠券
    * */
    @Transactional(readOnly = false)
    public boolean updateMyqponByEntity(CroMyqpon croMyqpon){
        try {
            croMyqponDao.update(croMyqpon);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
    /*添加新优惠券*/
    @Transactional(readOnly = false)
    public boolean addMyqponByEntity(CroMyqpon croMyqpon){
        try {
            croMyqponDao.save(croMyqpon);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /*查找优惠券是否已经领取*/
    @Transactional(readOnly = true)
    public boolean checkCoupons(String qid,String cid){
        String hql="from CroMyqpon where qId=? and costomid=?";
        if(croMyqponDao.get(hql,qid,cid)!=null){
            return false;
        }else {
            return true;
        }
    }

    /*
   * 分页查找出全部优惠券
   * */
    @Transactional(readOnly = true)
    public Pagination<CroMyqpon> findAllCoupons(int index, int size,String costomid){
        String hql="from CroMyqpon where del_flag='0' and costomid=?";
        Pagination<CroMyqpon> croMyqponList=croMyqponDao.findPagination(hql,index,size,costomid);
        return croMyqponList;
    }

}
